import $ from "jquery";
import Store from "store2";
import recordTpl from "./../components/record/index.ejs";

(($) => {
  const params = {
    record: Store.get("data") || [],
  };

  const methods = {
    formRecord: () => {
      const { record = [] } = params;
      return record.reduce((total, item, index, arr) => {
        if (total.length > 0 && total.some((_) => _.person == item.person)) {
          return total.map(_ => {
            if (_.person == item.person) {
              return Object.assign({}, _, {
                list: _.list.concat([item])
              })
            }
            return _;
          })
        }
        return total.concat([
          {
            person: item.person,
            list: [item],
          },
        ]);
      }, []);
    },

    fetchPersonList: () => {
      return new Promise((resolve, reject) => {
        $.ajax({
          type: "GET",
          url: "/data/data.json",
          success: (res) => {
            resolve({ data: res["people"] });
          },
          fail: (err) => {
            reject(err);
          },
        });
      });
    },

    initData: async () => {
      try {
        const { data = [] } = await methods.fetchPersonList();
        const recordList = methods.formRecord();
        const personList = recordList.map(_ => _.person);
        const noPerson = data.filter(_ => !personList.includes(_.user_name));
        const recordEl = recordTpl({
          count: recordList.length,
          record: recordList,
          noCount: noPerson.length,
          personList: noPerson,
        });
        $("body").append(recordEl)
      } catch (error) {
        console.error(error);
      }
    }
  };

  methods.initData();
  console.log(params);
})($);
